package cn.ac.sec.oil.data_analysis.calculation;

/**
 * 功能：根据平均值和标准差分析声波数据 计算float型数组中数据的标准差，数组长度可指定并且是float型的
 * GetAverageandStandardDevition：得到的平均值和标准偏差
 */
public class DataCalculation {

	private float averageValue = 0;
	public float max_SDevition = 0;
	public float levelPoint;

	/**
	 * 功能：从数组中逐次获取n个float数据计算标准差
	 */
	public int dataAnalysis(float[] fArray, int n) {

		int num = 0;
		int fArray_p = 0; // 指向fArray数组元素的指针,由此控制从fArray获取的元素
		float[] tempArray = new float[n]; // 创建长度为n的float数组
		float tmpSDevition;
		
		while(fArray_p + n <= fArray.length) {
			
			for (int i = 0; i < n; i++) { // 构建临时标准差计算数据数组

				tempArray[i] = fArray[i + fArray_p];
			}

			tmpSDevition = getStandardDevition(tempArray, n);
			if (averageValue >0 && fArray_p > 1000) {
				if (tmpSDevition > max_SDevition) {
					max_SDevition = tmpSDevition;
					levelPoint = tempArray[0];
				}
			}
			
			num = fArray_p + n;
			fArray_p ++;
		}
		return num;
	}

	/**
	 * 功能：获取平均值
	 */
	public float getAverage(float[] array) {
		
		float sum = 0;
		for (int i = 0; i < array.length; i++) {
			sum += array[i];
		}
		return (float) (sum / array.length);
	}

	/**
	 * 功能：获取标准差
	 */
	public float getStandardDevition(float[] array, int n) {

		float sum = 0;
		averageValue = getAverage(array);
		
		for (int i = 0; i < n; i++) {
			sum += (float) Math.pow(array[i] - averageValue, 2);
		}
		return (float) Math.sqrt(sum / (n - 1));
	}
}